/*
 * VirtualFile.cpp
 *
 *  Created on: Jul 23, 2009
 *      Author: kurt
 */

#include "VirtualFile.h"
#include "vfileops/vfileOpsFILE.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
using namespace objdraw;

VirtualFile::~VirtualFile() 
{
	if(funcs.close != NULL && stream != NULL)
		funcs.close(stream);
}
VirtualFile::VirtualFile() 
{
	memset(&funcs,0,sizeof(VirtualFileFunc));
	funcs.open = vFILE_open;
	funcs.close = vFILE_close;
	funcs.flush = vFILE_flush;
	funcs.seek = vFILE_seek;
	funcs.eof = vFILE_eof;
	funcs.tell = vFILE_tell;
	funcs.read = vFILE_read;
	funcs.write = vFILE_write;
	funcs.error = vFILE_error;
	funcs.geterror = NULL;
	funcs.is_open = vFILE_is_open;
	stream = NULL;
}
VirtualFile::VirtualFile(VirtualFileFunc ops)
{
	funcs = ops;
	stream = NULL;
}
VirtualFile::VirtualFile(VirtualFileFunc ops, void * _stream)
{
	funcs = ops;
	stream = stream;
}
VirtualFile::VirtualFile(const char * fname, const char * mode)
{
	memset(&funcs,0,sizeof(VirtualFileFunc));
	funcs.open = vFILE_open;
	funcs.close = vFILE_close;
	funcs.flush = vFILE_flush;
	funcs.seek = vFILE_seek;
	funcs.eof = vFILE_eof;
	funcs.tell = vFILE_tell;
	funcs.read = vFILE_read;
	funcs.write = vFILE_write;
	funcs.error = vFILE_error;
	funcs.geterror = NULL;
	funcs.is_open = vFILE_is_open;
	stream = NULL;
	if(funcs.open != NULL)
		funcs.open(fname,mode,stream);
}
bool VirtualFile::open(const char * fname, const char * mode)
{
	if(funcs.open != NULL)
		return funcs.open(fname,mode,stream);
	return false;
}
void VirtualFile::close()
{
	if(funcs.close != NULL)
		funcs.close(stream);
}
bool VirtualFile::eof()
{
	if(funcs.eof != NULL)
		return funcs.eof(stream);
	return false;
}
int VirtualFile::flush()
{
	if(funcs.flush != NULL)
		return funcs.flush(stream);
	return 0;
}
int VirtualFile::read(void * buffer, size_t size, size_t count)
{
	if(funcs.read != NULL)
		return funcs.read(buffer,size,count,stream);
	return 0;
}
int VirtualFile::write(const void * buffer, size_t size, size_t count)
{
	if(funcs.write != NULL)
		return funcs.write(buffer,size,count,stream);
	return 0;
}
int VirtualFile::seek(long offset, int origin)
{
	if(funcs.seek != NULL)
		return funcs.seek(stream,offset,origin);
	return 0;
}
long VirtualFile::tell()
{
	if(funcs.tell != NULL)
		return funcs.tell(stream);
	return 0;
}
bool VirtualFile::error()
{
	if(funcs.error != NULL)
		return funcs.error(stream);
	return false;
}
string VirtualFile::getError()
{
	if(funcs.geterror != NULL)
		return funcs.geterror(stream);
	return "Unknown";
}
bool VirtualFile::isOpen()
{
	if(funcs.is_open != NULL)
		return funcs.is_open(stream);
	if(stream != NULL)
		return true;
	return false;
}
string VirtualFile::toString()
{
//	TODO VirtualFile::toString()
	return "VirtualFile";
}

